package doweb

import (
	"fmt"
	"github.com/valyala/fasthttp"
	"manygo/doconfig"
	"manygo/dohttp"
	"manygo/mytools"
	"manygo/queue"
	"manygo/rabbitmq"
	"sync"
	"time"
)

//RunStatus 123
type RunStatus struct {
	NowNum  int
	LastNum int
	// IDMap  map[string]int8
	Queue *queue.Queue
}

//Result 123
type Result struct {
	// Stime    int64
	// Etime    int64
	UsedTime int64
	Send     int64
	Rev      int64
	Res      bool
}

//ErrResult 13
type ErrResult struct {
}

//Runner 13
var Runner *RunStatus

var rwlock sync.RWMutex
var closeNum chan byte
var runFunc func()
var rmq *rabbitmq.RabbitMQ

//Data 1231
// var Data *ReturnData

func init() {

	// Data = new(ReturnData)
	// Data.Records = make([]Result, 0)

}

//ClientStart 123
func ClientStart() {
	rmqr = rabbitmq.NewRabbitMQSimple("mqtbyres", "admin", "admin", "192.168.56.115", "5672", "/")
	if rmq == nil {
		panic("连接mq失败")
	}
	rmqt = rabbitmq.NewRabbitMQSimple("mqtbytime", "admin", "admin", "192.168.56.115", "5672", "/")
	rmqe = rabbitmq.NewRabbitMQSimple("mqtbyerr", "admin", "admin", "192.168.56.115", "5672", "/")

	Runner = &RunStatus{Queue: &queue.Queue{}}
	closeNum = make(chan byte, 50000)
	runFunc = moniTask
	ConnectMaster()
	go HeartBeat(1)
	AddRouter("GET", "/", Index)
	AddRouter("GET", "/heartbeatrestart", HeartBeatRestart)
	AddRouter("GET", "/heartbeatstop", HeartBeatStop)

	AddRouter("GET", "/checktask", SetCheckTask)
	AddRouter("GET", "/settask", SetTask)

	fmt.Println("running...http://127.0.0.1:9989")

	// go ManageTask(moniTask)

	Start("9989")

}

//SetTask 2342
func SetTask(ctx *fasthttp.RequestCtx) {
	if v, ok := doconfig.Config["heartbeatstop"]; ok {
		if v == "1" {
			fmt.Fprint(ctx, "no")
			return
		}
	}
	i, err := mytools.String2Int(string(ctx.FormValue("num")))
	if err == nil {
		// nu := Runner.MaxNum - i
		Runner.LastNum = i
		b := Runner.LastNum > Runner.NowNum
		nu := Runner.LastNum - Runner.NowNum
		Runner.NowNum = i
		fmt.Println(b, nu)

		if b {
			for x := 0; x < nu; x++ {

				go runFunc()

			}

		} else {
			go func() {
				for x := nu; x < 0; x++ {
					// fmt.Println("ss")
					closeNum <- '0'
					// fmt.Println("sss")

				}
			}()

		}

	}
	// string(ctx.FormValue("num"))

	fmt.Fprint(ctx, "ok")

}

//SetCheckTask 123
func SetCheckTask(ctx *fasthttp.RequestCtx) {
	// i, err := mytools.String2Int(string(ctx.FormValue("num")))
	// if err == nil {
	// 	Runner.MaxNum = i
	// 	finish <- i
	// }
	// string(ctx.FormValue("num"))

	fmt.Fprint(ctx, "ok")

}

func moniTask() {
L:
	for {
		if v, ok := doconfig.Config["heartbeatstop"]; ok {
			if v == "1" {
				break
			}

		}
		// rmq.PublishSimple(mytools.Binary2Bytes(Result{IsRun: false}))
		mytools.MySleepMs(1000)
		r := Result{int64( int64(10000), int64(mytools.RandIntn(100)), int64(mytools.RandIntn(10)), mytools.RandBool()}
		// fmt.Printf("%+v\n", r)
		// fmt.Println(mytools.Binary2Bytes(&r))
		rmqr.PublishSimple(mytools.Binary2Bytes(&r))
		select {
		case <-closeNum:
			// fmt.Println("eee")

			break L
		default:

		}

	}

	// finish <- 1
}

//HeartBeatRestart 13
func HeartBeatRestart(ctx *fasthttp.RequestCtx) {
	if v, ok := doconfig.Config["heartbeatstop"]; ok {
		if v == "1" {
			doconfig.Config["heartbeatstop"] = "0"
			go HeartBeat(1)
		}
	}

}

//HeartBeatStop 113
func HeartBeatStop(ctx *fasthttp.RequestCtx) {
	doconfig.Config["heartbeatstop"] = "1"
}

//ConnectMaster 获取服务端ip
func ConnectMaster() {
	if !SampleConnectIP(doconfig.Config["masterip"]) {
		for {
			v := mytools.MyInput("master ip?[xxx.xxx.xxx.xxx]")
			if SampleConnectIP(v) {
				doconfig.Config["masterip"] = v
				break
			}

		}
	}

}

//HeartBeat 定时心跳
func HeartBeat(t time.Duration) {
	for {
		// fmt.Println(1)

		if v, ok := doconfig.Config["heartbeatstop"]; ok {
			if v == "1" {
				// fmt.Println(2)
				break
			}
		}
		if !SampleConnect(doconfig.Config["masterip"]) {
			doconfig.Config["heartbeatstop"] = "1"
			// fmt.Println(3)
			break
		}
		// fmt.Println(4)
		time.Sleep(t * time.Second)
		// fmt.Println(5)
		// fmt.Println(t)
	}
}

//StartInit 检查本地是否有服务端
func StartInit() bool {
	_, err := dohttp.SampleGet("http://127.0.0.1:9988/heartbeatget")
	if err != nil {

		return false
	}
	return true

}

//SampleConnectIP 添加到服务端
func SampleConnectIP(ip string) bool {
	//完成时间所在秒的（每一条数据）
	v, err := dohttp.SampleGet("http://" + ip + ":9988/heartbeatadd")
	if err != nil {

		fmt.Println(err)

		return false
	}
	doconfig.Config["localip"] = v
	fmt.Println("success to connect " + ip)

	return true

}

//SampleConnect 连接服务端
func SampleConnect(ip string) bool {
	//完成时间所在秒的（每一条数据）
	v, err := dohttp.SampleGet("http://" + ip + ":9988/heartbeatconnect")
	if err != nil {

		fmt.Println(err)

		return false
	}
	// fmt.Println(v)

	return v == "ok"

}
